/*
 * @Author: Haochen
 * @Date: 2021-11-20 17:32:48
 * @LastEditTime: 2021-11-29 11:14:01
 * @FilePath: \front\src\js\login.js
 */

import '../scss/common.scss';
import '../scss/login.scss';

import $ from './jquery-3.6.0.min.js';
import { getPromise, getPromise1 } from './common.js';

$('#btn-to-register').click(function () {
  location.href = './register.html';
});

$('#btn-login').click(async function () {
  const obj = {
    logintel: $('#telephone').val(),
    loginpass: $('#password').val(),
  };

  const { message, code, token, user } = await getPromise1(
    '/students/login',
    'post',
    obj
  );

  if (code === 200) {
    let localUsersJson = localStorage.getItem('users');

    if (token) {
      localStorage.token = token;
    }

    if (localUsersJson == null) {
      // 这里是第一个用户的操作
      // 创建用户集合
      let localUsers = [];

      user.status = 'online';

      // 将用户信息追加到数组中

      localUsers.push(user);

      // 将用户数组对象变成JSON对象
      localUsersJson = JSON.stringify(localUsers);
      // 将用户JSON集合对象保存到localStorage中
      localStorage.setItem('users', localUsersJson);

      window.setTimeout(function () {
        alert(message);

        location.href = './index.html';
      }, 500);
    } else {
      // 表示已经有至少一个用户了
      // 首先将用户的json集合对象转换成js对象(即数组)
      let localUsers = JSON.parse(localUsersJson);
      const localUserIds = localUsers.map((localUser) => localUser._id);

      if (localUserIds.includes(user._id)) {
        localUsers = localUsers.map((localUser) => {
          if (localUser._id === user._id) {
            user.status = 'online';
            localUser = user;
            return localUser;
          } else {
            return localUser;
          }
        });
      } else {
        user.status = 'online';
        localUsers.push(user);
      }

      // 将js数组对象转成json对象
      localUsersJson = JSON.stringify(localUsers);
      // 将用户集合JSON对象保存到localStorage之中
      localStorage.setItem('users', localUsersJson);

      window.setTimeout(function () {
        alert(message);

        location.href = './index.html';
      }, 500);
    }
  } else {
    alert(message);
  }
});


